﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Microsoft.Practices.Unity;
using Vit.Common;
using Vit.Common.Extensions;
using Vit.Web.Providers;
using Vit.Web.Helpers;

namespace Vit.Web.Models
{
    public class Portal
    {
        public Portal()
        {
            Sites = new List<WebSite>();
        }

        [Key]
        [StringLength(50)]
        public string ID { get; set; }

        [StringLength(50)]
        public string Caption { get; set; }

        [StringLength(500)]
        public string ImageUrl { get; set; }

        [StringLength(500)]
        public string Description { get; set; }

        public virtual ICollection<WebSite> Sites { get; set; }

        public bool AddSite(WebSite site)
        {
            bool isCurrentPortal = PortalContext.Current.Portal.ID == this.ID;
            bool result = Unity.Current.ResolveAny<IPortalProvider>().ForEach<IPortalProvider, bool>(p => p.AddSite(this, site));
            if (result && isCurrentPortal)
                RefreshCurrentPortal();
            return result;
        }

        public bool UpdateSite(WebSite site)
        {
            bool isCurrentPortal = PortalContext.Current.Portal.ID == this.ID;
            bool result = Unity.Current.ResolveAny<IPortalProvider>().ForEach<IPortalProvider, bool>(p => p.UpdateSite(this, site));
            if (result && isCurrentPortal)
                RefreshCurrentPortal();
            return result;
        }

        public bool RemoveSite(string siteId)
        {
            bool isCurrentPortal = PortalContext.Current.Portal.ID == this.ID;
            bool result = Unity.Current.ResolveAny<IPortalProvider>().ForEach<IPortalProvider, bool>(p => p.RemoveSite(this, siteId));
            if (result && isCurrentPortal)
                RefreshCurrentPortal();
            return result;
        }

        public void RefreshCurrentPortal()
        {
            HttpContext.Current.Application.Remove("CurrentPortal");
            HttpContext.Current.Session.Remove("CurrentSite");
        }
    }
}
